<template>
  <div class="homework-page">
    <input class="search-box" type="text" v-model="searchKeyword" placeholder="搜索作业标题..." />

    <Row>
      <Col class="calendar-div" span="8" offset="2">
        <div class="cell"  @click="show = true">
          {{date}}
          <img slot="icon" src="../../assets/images/calendar.png" style="width: 20px;margin-left: 10px;"/>
        </div>
        <calendar v-model:show="show" color="#a3d33b" @confirm="onConfirm" :min-date="new Date(1990, 0, 1)"/>
      </Col>

    </Row>

    <div  class="homework-content">
      <div class="homework-list-container">
        <SwipeCell v-for="homework in filterByKeyword" :key="homework.id"
                   @open="handleSwipeOpen(homework.id)"
                   @close="handleSwipeClose(homework.id)">
          <div class="homework-item" @click="goToDetail(homework)">
            <div class="homework-title-box">
              <div class="homework-title">{{ homework.title }}</div>
              <div class="homework-detail">
                <!-- 作业内容摘要 -->
                <div class="homework-preview">
                  <div class="homework-preview-content" v-html="homework.content.length > 50 ? homework.content.slice(0, 50) + '...' : homework.content"></div>
                </div>
                <div class="homework-grade" v-if="Local.get('userInfo').role === 2 || Local.get('userInfo').role === 3">
                  成绩：<span class="grade-value">{{ homework.score }}</span>
                </div>
                <div class="homework-info">
                  <span class="homework-teacher">老师：{{ homework.teacherName }}</span>
                  <span class="homework-date" style="color: gray; font-size: smaller;margin-left: 100px">日期：{{ formatDate(homework.time) }}</span>
                </div>
              </div>
            </div>
          </div>
          <template #right v-if="Local.get('userInfo').role === 1">
            <Row style="margin-top: 40px">
              <div @click="openEditModal(homework)">
                <img src="../../assets/icons/edit.png" class="icon"/>
              </div>
              <div @click="confirmDelete(homework.homeworkId)">
                <img src="../../assets/icons/delete.png" class="delete-icon"/>

              </div>
            </Row>
          </template>
        </SwipeCell>
      </div>
    </div>
  </div>
  <EditHomeworkModal ref="editHomeworkModal" @close="handleModalClose"/>

</template>

<script setup>
import {ref, computed, onMounted, watch, nextTick ,reactive} from 'vue';
import axios from 'axios';
import router from "@/router";
import {Calendar,SwipeCell, Row, Col,Dialog} from "vant";
import {Local} from "@/utils/storage";
import EditHomeworkModal from '@/components/GridCard/EditHomeworkModal.vue';

const date = ref('请选择时间');
const homeworkList = ref([]);
const searchKeyword = ref(''); // 响应式变量存储搜索关键词
const selectedDate = ref(null); // 存储选定日期的响应式变量
const show = ref(false); // 添加日历显示控制变量


onMounted(async () => {
  await getHomeworkList();
  await nextTick(() => {
    // 这里的代码会在DOM更新完成后执行
    getHomeworkList();
  });
  const userInfo = await Local.get('userInfo');

});



//添加 watch 监听
watch(searchKeyword, (newKeyword) => {
  if (newKeyword) {
    selectedDate.value = null; // 当搜索框有内容时，重置日期选择器
  }
});

const getHomeworkList = async () => {
  try {
    const response = await axios.get('/api/homework/assignments');
    // 首先，将时间转换为Date对象
    const homeworkData = response.data.map(item => ({
      ...item,
      time: new Date(item.time),
    }));

    // 检查用户角色，如果是2或3，继续获取成绩
    const userInfo = Local.get('userInfo');
    if (userInfo && (userInfo.role === 2 || userInfo.role === 3)) {
      // 使用Promise.all来等待所有成绩获取完成
      await Promise.all(homeworkData.map(async (homework) => {
        const studentId = userInfo.userId; // 确保userInfo中确实有userId属性
        const scoreResponse = await axios.get(`/api/homework/completionStatus/${studentId}/${homework.homeworkId}`);
        if (scoreResponse.data && scoreResponse.data.score !== undefined) {
          homework.score = scoreResponse.data.score; // 假设后端返回的成绩在data.score中
        }
      }));
    }

    homeworkList.value = homeworkData;
  } catch (error) {
    console.error('Failed to fetch homework list:', error);
  }
};

// 根据关键字筛选的计算属性
const filterByKeyword = computed(() => {
  // 当没有选定日期且搜索框为空时，显示所有作业
  if (!selectedDate.value && !searchKeyword.value) {
    return homeworkList.value;
  }
  // 根据日期或关键字进行筛选
  return homeworkList.value.filter(homework => {
    const isDateMatch = selectedDate.value ? formatDate(homework.time) === formatDate(selectedDate.value) : true;
    const isKeywordMatch = searchKeyword.value ? homework.title.toLowerCase().includes(searchKeyword.value.toLowerCase()) : true;
    return isDateMatch && isKeywordMatch;
  });
});


const onConfirm = (dateObject) => {
  selectedDate.value = formatDate(dateObject); // 更新 selectedDate 为格式化的日期字符串
  searchKeyword.value = ''; // 重置搜索框内容
  show.value = false; // 隐藏日历
};

// 格式化日期的函数，确保只返回日期部分
const formatDate = (date) => {
  if (!(date instanceof Date)) {
    // 尝试转换日期，如果失败则返回一个默认值或空字符串
    date = new Date(date);
  }
  // 使用 toLocaleDateString 来格式化日期，避免 Invalid Date 问题
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};


//跳转到详情页面
const goToDetail = (homework) => {
  const homeworkString = JSON.stringify(homework);
  if (Local.get('userInfo').role === 2 || Local.get('userInfo').role === 3) {
    router.push({
      name: 'homeworkparstu',
      query: {
        homework: homeworkString
      }
    });
  } else {

    router.push({
      name: 'homeworkdetail', // 确保名称与路由配置一致
      query: {
        homework: homeworkString
      }
    }).catch(err => {
      // 在 Vue Router 4 中，如果导航被阻止，catch 块会被调用
      console.error('Navigation failed:', err);
    });
  }
};


const editHomeworkModal = ref(null);
const openEditModal = (homeworkData) => {
  console.log('homeworkData:', homeworkData)
  editHomeworkModal.value.open({
    id: homeworkData.homeworkId,
    title: homeworkData.title,
    content: homeworkData.content,
    finishdate: homeworkData.finishdate,
  });

};
const handleModalClose = () => {
  getHomeworkList();
};
const confirmDelete = async (homeworkId) => {

  console.log("删除作业的id："+homeworkId)
  if (typeof homeworkId !== 'number') {
    console.error('homeworkId is not a number');
    return;
  }
  Dialog.confirm({
    title: '删除作业',
    message: '确定要删除这项作业吗？',
  })
      .then(async () => {
        // on confirm
        try {
          const response = await axios.delete(`/api/homework/deleteHomework/${homeworkId}`);
          if (response.status === 200) { // 或者 response.ok
            // 处理成功情况
            homeworkList.value = homeworkList.value.filter(item => item.id !== homeworkId);
            Dialog.alert({
              title: '删除成功',
            });
            getHomeworkList();
          } else {
            // 处理错误情况
            Dialog.alert({
              title: '删除失败',
              message: '未知错误',
            });

          }
        } catch (error) {
          // 捕获错误，弹出删除失败的提示
          console.error('Delete failed:', error);
          Dialog.alert({
            title: '错误',
            message: '删除时发生错误，请稍后重试。',
          });
        }
      })
      .catch(() => {
        // on cancel

      });
};

</script>





<style scoped>


.cell {
  /* //width: 100%; */
  height: 100%;
  text-align: left;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14.5px;
  color: gray;
}

.icon{
  width: 25px;
  height: 25px;
}
.delete-icon{
  width: 18px;
  height: 18px;
  margin-left: 5px;

}
.calendar-div {
  width: 120px;
  height: 35px;
  border: 1px solid #9caf70;
  border-radius: 7px;
  font-size: 16px;


  :deep(.van-dropdown-menu__bar) {
    box-shadow: unset !important;
    background-color: transparent !important;
    height: 20px !important;

  }

  :deep(.van-popup) {
    width: 33% !important;
    right: 8% !important;
    left: auto;
    top: 1px;
  }

  :deep(.titleClass) {
    color: grey !important;
  }

  :deep(.van-dropdown-item__content .van-cell__title) {
    flex: 2 !important;
  }
}

.homework-item {
  display: flex; /* 使用flex布局以使子元素水平排列 */
  height: 100px;
  margin: 10px;
  align-items: center; /* 垂直居中子元素 */
  justify-content: space-between; /* 水平分布子元素 */
  border: 2px solid  #9caf70;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影效 */
}

.homework-title-box {
  font-size: 18px; /* 标题字体大小 */
  overflow: hidden; /* 防止标题溢出 */
  white-space: nowrap; /* 不换行 */
  text-overflow: ellipsis; /* 溢出用省略号表示 */
  color: #1e1f22;
}

.homework-title {
  font-size: 16px; /* 标题字体大小 */
  font-weight: bold; /* 粗体 */
  margin-bottom: 2px; /* 标题与摘要之间的间距 */
  color: rgba(51, 51, 51, 0.83); /* 标题颜色 */
  margin: 5px;
}


.homework-preview-content {
  margin: 5px; /* 重置文字的默认外边距 */
  overflow: hidden; /* 防止文字溢出 */
  text-overflow: ellipsis; /* 溢出用省略号表示 */
  font-size: 14px;
  color: #6a6c6e;
  height: 25px; /* 固定主体高度 */
}

.homework-info {
  font-size: 12px; /* 信息字体大小 */
  color: #888; /* 信息颜色 */
  margin-bottom: 8px;
}

.homework-teacher {
  margin-bottom: 8px;
  margin-left: 5px;
  margin-right: 50px;
}

.homework-date {
  color: #bbb; /* 日期颜色 */
  font-size: 12px; /* 日期字体大小 */
  margin-bottom: 8px;

}

/* 搜索框样式 */
.search-box {
  margin: 10px 20px; /* 上下边距，左右自动 */
  padding: 8px 15px; /* 内边距 */
  width: 80%; /* 宽度减去内边距的两倍 */
  border: 2px solid  #9caf70;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影效 */
  outline: none; /* 点击时不显示轮廓 */
  font-size: 16px; /* 字体大小 */
}


/* 作业内容样式 */
.homework-content {
  padding: 10px;
  border-radius: 8px; /* 圆角边框 */
  margin: 5px;

}
.homework-grade {
  font-size: 14px;
  color: #6a6c6e;
  margin-bottom: 2px; /* 与教师姓名和日期信息的间距 */
  margin-left: 5px;
}

.grade-value {
  font-weight: bold; /* 加粗成绩数值 */
  color: #ff6347; /* 改变成绩数值的颜色，例如红色 */
}
</style>
